#ifndef __TCP_CLIENT_HPP__
#define __TCP_CLIENT_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "./ThreadPool/Log.hpp"

#define SIZE 1024

class TCPClient
{
public:
    TCPClient(uint16_t serPort,std::string serIp)
        :_serPort(serPort)
        ,_serIp(serIp)
        ,_sock(-1)
    {}

    void initClient()
    {
        //获取套接字
        _sock=socket(AF_INET,SOCK_STREAM,0);
        if(_sock<0)
        {
            logMessage(FATAL,"socket:%s\n",strerror(errno));
            exit(2);
        }

        //connect
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(_serPort);
        server.sin_addr.s_addr=inet_addr(_serIp.c_str());
        if(connect(_sock,(struct sockaddr*)&server,sizeof(server))<0)
        {
            logMessage(FATAL,"connect:%s\n",strerror(errno));
            exit(3);
        }
    }

    void start()
    {
        char buff[SIZE];
        while(true)
        {
            std::string message;
            std::getline(std::cin,message);
            if(message=="quit")
            {
                break;
            }
            send(_sock,message.c_str(),message.size(),0);
            
            memset(buff,0,sizeof(buff));
            ssize_t s=recv(_sock,buff,SIZE-1,0);
            if(s>0)
            {
                buff[s]='\0';
                logMessage(NORMAL,"server# %s\n",buff);
            }
        }
    }

    ~TCPClient()
    {
        close(_sock);
    }

private:
    uint16_t _serPort;
    std::string _serIp;
    int _sock;
};

#endif